package com.rdl.main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import com.rdl.grammer.ParseException;
import com.rdl.grammer.RdlParser;
import com.rdl.relation.DatabaseInfo;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class RDLEntry {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
//			if(args.length < 2){
//				System.out.println("input error");
//				PrintUsage();
//				System.exit(1);
//			}
			
//			RdlParser parser = new RdlParser(
//					new FileInputStream(args[0]));
			RdlParser parser = new RdlParser(
					new FileInputStream("input"));
//			parser.enable_tracing();
			DatabaseInfo database = parser.Start();
			
			Configuration ftlConfig = new Configuration();
			try {
				ftlConfig.setDirectoryForTemplateLoading(new File("template"));
				ftlConfig.setObjectWrapper(new DefaultObjectWrapper());
				
				@SuppressWarnings("rawtypes")
				Map root = new HashMap();
				
				root.put("database", database);
//				Writer out = new OutputStreamWriter(
//						new FileOutputStream(args[1] + ".out"));
				Writer out = new OutputStreamWriter(System.out);
				OutUseTemplate("sql.ftl", out, root, ftlConfig);
				OutUseTemplate("idl_dao.ftl", out, root, ftlConfig);
				OutUseTemplate("dao_impl.ftl", out, root, ftlConfig);
				OutUseTemplate("ddo_fromdb.ftl", out, root, ftlConfig);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TemplateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (FileNotFoundException e) {
			System.out.println(args[1] + " is not found");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static void OutUseTemplate(String templateName,
			Writer out, @SuppressWarnings("rawtypes") Map root, Configuration ftlConfig) throws IOException, TemplateException
	{
		Template template = ftlConfig.getTemplate(templateName);
		template.process(root, out);
		out.flush();
	}
	
	private static void PrintUsage(){
		System.out.println("rdl input target");
	}

}
